package 二叉树.练习;

import 二叉树.基础.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
//二叉树的分层遍历
public class Text_8 {
    public List<List<Character>> levelOrder(TreeNode root) {
        List<List<Character>> ret = new ArrayList<>();
        if (root == null) {
            return ret;
        }
        //队列，大的存放
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            //每层存放的
            List<Character> tmp = new LinkedList<>();
            int size = queue.size();
            while (size != 0) {
                TreeNode cur = queue.poll();
                tmp.add(cur.val);
                size--;
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
            }
//        每层的元素都放在了tmp里，再将tmp给ret
            ret.add(tmp);
        }
        return ret;
    }
}

